/**
 * 吾帮你 v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import ProLayout from '@ant-design/pro-layout';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useIntl, connect, history } from 'umi';
import { Result, Button, Input, Badge } from 'antd';
import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import { getMatchMenu } from '@umijs/route-utils';
import { SearchOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { getFetch } from '@/utils/doFetch';

const noMatch = (
  <Result
    status={403}
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={
      <Button type="primary">
        <Link to="/user/login">返回登录</Link>
      </Button>
    }
  />
);

const defaultFooterDom = (
  <a style={{ textAlign: 'center', marginBottom: 12, color: '#999' }}>优天辰集团体验技术部出品</a>
);

const BasicLayout = (props) => {
  const {
    dispatch,
    children,
    settings,
    user,
    location = {
      pathname: '/',
    },
  } = props;
  const menuDataRef = useRef([]);
  const [keyWord, setKeyWord] = useState('');
  useEffect(() => {
    window.dataconfig = {
      tableMethod: 'GET',
      tableTokenkey: 'Authorization',
      serverURL: '/wbn-api/file',
    };
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
      });
    }
  }, []);
  /**
   * init variables
   */

  const handleMenuCollapse = (payload) => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  }; // get children authority

  const authorized = useMemo(
    () =>
      getMatchMenu(location.pathname || '/', menuDataRef.current).pop() || {
        authority: undefined,
      },
    [location.pathname],
  );
  const { formatMessage } = useIntl();

  const filterByMenuDate = (data, keyWord) => {
    return data
      .map((item) => {
        if (
          (item.name && item.name.includes(keyWord)) ||
          filterByMenuDate(item.children || [], keyWord).length > 0
        ) {
          return {
            ...item,
            children: filterByMenuDate(item.children || [], keyWord),
          };
        }
        return undefined;
      })
      .filter((item) => item);
  };

  const menuDataRender = (menuList) => {
    let res = user.currentUser;
    let filterlist = res?.menus ? res.menus : [],
      patharr = filterlist.map((it) => it.path);
    let firstpatharr = [...new Set(patharr.map((it) => `/${it.split('/')[1]}`))];

    let menudata = menuList
      .filter((it) => {
        return firstpatharr.indexOf(it.path) != -1;
      })
      .map((item) => {
        let child = item.routes
          ? item.routes.filter((its) => {
              return patharr.includes(its.path);
            })
          : undefined;
        const localItem = {
          ...item,
          children: child,
        };
        return localItem;
      });
    return menudata;
  };

  const hasActiveMessage = useRequest(
    async () => {
      let res = await getFetch({
        url: '/wbn-api/wechat/employee/company',
        params: {
          is_chat: 1,
          pageIndex: 1,
        },
      });
      const hasNoread = res?.data?.list.some((it) => it.unread_num > 0) ?? false;
      return hasNoread;
    },
    {
      // pollingInterval: 3000,
    },
  );

  return (
    <ProLayout
      {...props}
      {...settings}
      //logo={logo}
      fixedHeader={true}
      formatMessage={formatMessage}
      menu={{ locale: false }}
      onCollapse={handleMenuCollapse}
      onMenuHeaderClick={() => history.push('/')}
      subMenuItemRender={(menuItemProps, dom) => {
        if (menuItemProps.path === '/feedback' && hasActiveMessage?.data === true) {
          return <Badge dot>{dom}</Badge>;
        }
        return dom;
      }}
      menuItemRender={(menuItemProps, defaultDom) => {
        let dom = defaultDom;
        if (
          menuItemProps.isUrl ||
          !menuItemProps.path ||
          location.pathname === menuItemProps.path
        ) {
          dom = defaultDom;
        }

        dom = <Link to={menuItemProps.path} style={{color:"#fff"}}>{defaultDom}</Link>;
        if (menuItemProps.path === '/feedback/online' &&  hasActiveMessage?.data === true) {
          dom = <Badge dot>{dom}</Badge>
        }

        return dom;
      }}
      breadcrumbRender={(routers = []) => [
        {
          path: '/',
          breadcrumbName: formatMessage({
            id: 'menu.home',
          }),
        },
        ...routers,
      ]}
      itemRender={(route, params, routes, paths) => {
        const first = routes.indexOf(route) === 0;
        return first ? (
          <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
        ) : (
          <span>{route.breadcrumbName}</span>
        );
      }}
      footerRender={() => defaultFooterDom}
      menuDataRender={menuDataRender} //切换数据 menuDataRenders全部菜单 menuDataRender个人菜单
      headerContentRender={() => <RightContent />}
      menuExtraRender={({ collapsed }) =>
        !collapsed && (
          <Input
            prefix={<SearchOutlined />}
            placeholder="搜索菜单"
            style={{ overflow: 'hidden' }}
            onChange={(e) => {
              setKeyWord(e.target.value);
            }}
          />
        )
      }
      postMenuData={(menus) => filterByMenuDate(menus || [], keyWord)}
    >
      <Authorized authority={authorized.authority} noMatch={noMatch}>
        {children}
      </Authorized>
    </ProLayout>
  );
};

export default connect(({ global, settings, user }) => ({
  collapsed: global.collapsed,
  settings,
  user,
}))(BasicLayout);
